require File.dirname(__FILE__) + '/initializers'

class StorageManager
  include OpenWFE
  
  # StorageManager Constuctor
  def initialize
    load_configurations
    load_application_log
  end
  
  def start_management
    # Initialize scheduler process
    @scheduler = Scheduler.new
    @scheduler.start
    
    # Schedules daemon to fetch assets
    @fetch_job = @scheduler.schedule_every "#{@fetch_interval}" do
      fetch_assets
    end
    
    # Schedules daemon to replicate assets
    @replicate_job = @scheduler.schedule_every "#{@replication_interval}" do
      replicate_assets
    end
  end
  
  # Fetch marked assets
  def fetch_assets
    fetchers = Fetcher.find_get_fetchers
    
    fetchers.each do |fetcher|
      fetcher.fetch
    end
  end
  
  # Replicate marked assets
  def replicate_assets
    fetchers = Fetcher.find_put_fetchers
    
    fetchers.each do |fetcher|
      fetcher.replicate
    end
  end

  def end_management
    # Closes schedule processes
    @schedule.unschedule(@fetch_job)
    @schedule.unschedule(@replicate_job)

    # Closes application log
    @log.close
  end
  
  # Sets application log
  def load_application_log
    file = File.open(RadiaStore::LOG, File::WRONLY | File::APPEND)
    @log = Logger.new(file, 'daily')
    @log.level = Logger::DEBUG
    @log.datetime_format = "%Y-%m-%d %H:%M:%S"
  end
  
  # Load application configurations specified in APP_CONFIG_FILE file
  def load_configurations
    app_configurations = YAML.load_file RadiaStore::APP_CONFIG_FILE
    @replication_interval = app_configurations['replication_interval']
    @fetch_interval = app_configurations['fetch_interval']
  end
  
  # Logs messages in log file
  def logging(msg, exception = nil)
    @log.info Time.now.to_s + " #{msg}\n"
    @log.error exception.to_s + "\n" unless exception.nil?
  end
end